package com.toweave.starter.components;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.BlurMaskFilter;
import android.graphics.Paint;
import android.view.View;
import android.util.AttributeSet;

import androidx.annotation.ColorInt;
import androidx.annotation.Dimension;

import com.toweave.starter.R;

public class PieChart extends View {
  private boolean mShowText;
  private int textPos;
  private Paint textPaint;
  private Paint piePaint;
  private Paint shadowPaint;

  private Boolean showText;    // Obtained from styled attributes.
  private int textWidth;       // Obtained from styled attributes.


  public PieChart(Context context, AttributeSet attrs) {
    super(context, attrs);

    TypedArray a = context.getTheme().obtainStyledAttributes(
        attrs,
        R.styleable.PieChart,
        0, 0);

    try {
      mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
      textPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
    } finally {
      a.recycle();
    }
  }

  public boolean isShowText() {
    return mShowText;
  }

  public void setShowText(boolean showText) {
    mShowText = showText;
    invalidate();
    requestLayout();
  }

  @ColorInt
  private int textColor;       // Obtained from style attributes.

  @Dimension
  private float textHeight;    // Obtained from style attributes.

  private void init() {
    textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    textPaint.setColor(textColor);
    if (textHeight == 0) {
      textHeight = textPaint.getTextSize();
    } else {
      textPaint.setTextSize(textHeight);
    }

    piePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
    piePaint.setStyle(Paint.Style.FILL);
    piePaint.setTextSize(textHeight);

    shadowPaint = new Paint(0);
    shadowPaint.setColor(0xff101010);
    shadowPaint.setMaskFilter(new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL));
  }


  @Override
  protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    super.onSizeChanged(w, h, oldw, oldh);
    // Account for padding.
    float xpad = (float) (getPaddingLeft() + getPaddingRight());
    float ypad = (float) (getPaddingTop() + getPaddingBottom());

    // Account for the label.
    if (showText) xpad += textWidth;

    float ww = (float) w - xpad;
    float hh = (float) h - ypad;

    // Figure out how big you can make the pie.
    float diameter = Math.min(ww, hh);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    // Try for a width based on your minimum.
    int minw = getPaddingLeft() + getPaddingRight() + getSuggestedMinimumWidth();
    int w = resolveSizeAndState(minw, widthMeasureSpec, 1);

    // Whatever the width is, ask for a height that lets the pie get as big as it
    // can.
    int minh = MeasureSpec.getSize(w) - (int) textWidth + getPaddingBottom() + getPaddingTop();
    int h = resolveSizeAndState(minh, heightMeasureSpec, 0);

    setMeasuredDimension(w, h);
  }
}